package com.fantasy.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import com.fantasy.ui.MessageSpec;
import com.fantasy.util.IMUtil;

import android.util.Log;

public class SocketProcesser {
	private static final String TAG = "SocketProcesser";
	private static final boolean DEBUG = true;
	private static final int ECHOMAX = 255;

	// private static SocketProcesser sInstance;
	private static DatagramSocket mSocket;
	private static DatagramPacket mReceivedPacket;

	private boolean isEnabled = false;

	public boolean getProcesserEnable() {
		return isEnabled;
	}

	public void startMessage() {
		isEnabled = true;
	}

	/**
	 * get class instance
	 * 
	 * @return
	 * @throws SocketException
	 */
	public static void getInstance() throws SocketException {

		mSocket = new DatagramSocket(IMUtil.IM_SOCKET_PORT);
		mReceivedPacket = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);
		// return sInstance;
	}

	public MessageSpec receiveMessage() throws IOException {
		Log.d(TAG,"@@@start_receiveMessage:");
		mSocket.receive(mReceivedPacket);
		Log.d(TAG,"@@@@receivedMessage");
		MessageSpec msg = new MessageSpec();
		msg.messageContent = new String(mReceivedPacket.getData());
		msg.mSenderIP = mReceivedPacket.getAddress().getHostAddress();
		msg.messgePort = mReceivedPacket.getPort();
		return msg;

	}

	public void sendMessage(MessageSpec message, MessageSpec target)
			throws IOException {
		if (DEBUG) {
			Log.d(TAG, "sendMessage:>>" + message.messageContent);
		}

		while (isEnabled) {
			Log.d(TAG, "start receving message");
			byte[] result = message.messageContent.getBytes();
			int length = result.length;
			int port = target.messgePort;
			InetAddress targetAddress = InetAddress.getByName(target.mSenderIP);
			
			DatagramPacket packet = new DatagramPacket(result, length,
					targetAddress, port);
			mSocket.send(packet);
			packet.setLength(ECHOMAX);

		}
	}
}
